package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //当前集合用于存放从begin到end范围内的每天的日期
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            //日期计算，计算指定日期的后一天对应的日期
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            //查询date日期对应的营业额数据，营业额是指：状态为“已完成”的订单金额合计
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);//当天00:00:00
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//当天23:59:59
            //select sum(amount) from orders where order_time > beginTime and order_time < endTime and status = 5
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            map.put("status", Orders.COMPLETED);
//            orderMapper.sumByMap(
//                    Orders.COMPLETED,
//                    beginTime,
//                    endTime
//            );
            Double turnover=orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);

        }


        //使用StringUtils工具类将dateList集合转换为逗号分隔的字符串
        String join = StringUtils.join(dateList, ",");

        //封装返回结果
        return TurnoverReportVO.builder()
                .dateList(join)
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 统计指定时间内的用户统计
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //当前集合用于存放从begin到end范围内的每天的日期
        List<LocalDate> dateList1 = new ArrayList<>();
        dateList1.add(begin);
        while (!begin.equals(end)) {
            //日期计算，计算指定日期的后一天对应的日期
            begin = begin.plusDays(1);
            dateList1.add(begin);
        }

        //存放每天的新增用户数量 select count(id) from user where create_time > beginTime and create_time < endTime
        List<Integer> newUserList = new ArrayList<>();
        //存放每天的总用户数量 select count(id) from user where create_time < endTime
        List<Integer>totalUserList = new ArrayList<>();
        for (LocalDate date : dateList1) {
            //查询date日期对应的营业额数据，营业额是指：状态为“已完成”的订单金额合计
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);//当天00:00:00
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//当天23:59:59
            Map map = new HashMap();
            map.put("end", endTime);

            //总用户数量
            Integer totalUser = userMapper.countByMap(map);
            map.put("begin", beginTime);
            //新增用户数量
            Integer newUser = userMapper.countByMap(map);
            totalUserList.add(totalUser);
            newUserList.add(newUser);
            newUser = newUser == null ? 0 : newUser;
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList1, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    /**
     * 统计指定时间内的订单统计
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //当前集合用于存放从begin到end范围内的每天的日期
        List<LocalDate> dateList2 = new ArrayList<>();
        dateList2.add(begin);
        while (!begin.equals(end)) {
            //日期计算，计算指定日期的后一天对应的日期
            begin = begin.plusDays(1);
            dateList2.add(begin);
        }
        //存放每天订单总数
        List<Integer> orderCountList = new ArrayList<>();
        //存放每天有效订单数量
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList2) {
            //查询date日期对应的营业额数据，营业额是指：状态为“已完成”的订单金额合计
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);//当天00:00:00
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);//当天23:59:59
//            Map map = new HashMap();
//            map.put("begin", beginTime);
//            map.put("end", endTime);
            //订单总数
            Integer orderCount = getOrderCount(beginTime, endTime, null);
            //订单总数
//            Integer orderCount = orderMapper.countByMap(map);
            orderCountList.add(orderCount);
//            map.put("status", Orders.COMPLETED);
            //有效订单数量
            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);
//            Integer validOrderCount = orderMapper.countByMap(map);
            validOrderCountList.add(validOrderCount);
        }
        //订单总数求和
//        int orderSum = orderCountList.stream().mapToInt(Integer::intValue).sum();
//        //有效订单数量求和
//        int validOrderSum = validOrderCountList.stream().mapToInt(Integer::intValue).sum();
        //订单总数求和
        Integer totalOrderSum = orderCountList.stream().reduce(Integer::sum).get();
        //有效订单数量求和
        Integer validOrderSum = validOrderCountList.stream().reduce(Integer::sum).get();
        //订单完成率
//        Double orderCompletionRate = Math.round(validOrderSum * 100.0 / totalOrderSum) / 100.0;
        Double orderCompletionRate=0.0;
        if (totalOrderSum != 0) {
           orderCompletionRate = validOrderSum.doubleValue() / totalOrderSum;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList2, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderSum)
                .validOrderCount(validOrderSum)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end,Integer status) {
        Map map = new HashMap();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);
        return orderMapper.countByMap(map);
    }

    /**
     * 统计指定时间内的销量排名
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
//        List<LocalDate> dateList2 = new ArrayList<>();
//        dateList2.add(begin);
//        while (!begin.equals(end)) {
//            //日期计算，计算指定日期的后一天对应的日期
//            begin = begin.plusDays(1);
//            dateList2.add(begin);
//        }
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);//当天00:00:00
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);//当天23:59:59
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());//获取商品名称
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());//获取商品数量
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(names, ","))
                .numberList(StringUtils.join(numbers, ","))
                .build();
    }

    /**
     * 导出营业数据报表
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //1、查看数据库，获取营业数据--查询最近30天的运营数据
        LocalDate datebegin = LocalDate.now().minusDays(30);//获取当前时间减去30天的日期
        LocalDate dateEnd = LocalDate.now().minusDays(1);//获取当前时间减去1天的日期（也就是昨天的日期），因为今天的数据还没有处理完。
        LocalDateTime begin = LocalDateTime.of(datebegin, LocalTime.MIN);//当天00:00:00
        LocalDateTime end = LocalDateTime.of(dateEnd, LocalTime.MAX);//当天23:59:59
        //查询概览数据
        BusinessDataVO businessData = workspaceService.getBusinessData(begin, end);
        //2、通过POI将数据写入excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        //this.getClass().getClassLoader()
        //获取当前类的类加载器(ClassLoader)
        //类加载器负责在JVM中加载和查找类及资源文件
        //getResourceAsStream("template/运营数据报表模拟.xlsx")
        //使用类加载器的getResourceAsStream方法
        //从classpath路径下查找并打开指定的资源文件
        //参数是资源文件的相对路径
        //功能作用
        //读取Excel模板文件：从项目的资源目录中加载名为"运营数据报表模拟.xlsx"的Excel文件
        //创建输入流：返回InputStream对象，可用于后续的文件读取操作

        //基于模板文件创建一个新的excel对象
        try {
            XSSFWorkbook excel = new XSSFWorkbook(in);
            //获取表格文件的sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间:"+datebegin + "至" + dateEnd);

            //获取第四行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());
            //获取第五行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            //填充明细数据
            for (int i = 0; i <30; i++) {
                LocalDate date = datebegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN),LocalDateTime.of(date,LocalTime.MAX));
                //获取某一行
                row = sheet.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            }
            //3、通过输出流将excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            //关闭资源
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
